package com.mo2323.merchant.secruity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mo2323.common.VO;
import com.mo2323.common.util.DateUtils;
import com.mo2323.merchant.secruity.user.User;
import com.mo2323.service.merchant.IUserAuthService;
import com.mo2323.service.merchant.IUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 28876
 */
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
    @Reference
    private IUserService userService;
    @Reference(version = "11")
    private IUserAuthService userAuthService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        try {
            return doLoadUserByUnionId(userName);
        } catch (Exception e) {
            try {
                return doLoadUserByUserName(userName);
            } catch (Exception e1) {
                throw new UsernameNotFoundException(String.format("getUserAuthInfo Exception：%s.", e1.getMessage()));
            }
        }
    }

    private UserDetails doLoadUserByUnionId(String unionId) throws UsernameNotFoundException {
        try {
            VO userAuthVO = userAuthService.getUserAuthInfo(unionId);
            User user = new User();
            user.setUsername(userAuthVO.getString("union_id"));
            user.setId(userAuthVO.getString("id"));
            //可以通过修改密码重置时间，来注销特定Token的授权
            user.setLastPasswordResetDate(DateUtils.convertStringToDate(userAuthVO.getString("last_reset_time"), "yyyy-MM-dd HH:mm:ss"));
            user.setPassword(userAuthVO.getString("union_id").toLowerCase());
            return JwtUserFactory.create(user);
        } catch (Exception e) {
            throw new UsernameNotFoundException(String.format("getUserAuthInfo Exception：%s.", e.getMessage()));
        }
    }

    private UserDetails doLoadUserByUserName(String userName) throws UsernameNotFoundException {
        try {
            VO vo = userService.getUserInfoByName(userName);
            User user = new User();
            user.setUsername(vo.getString("username"));
            user.setId(vo.getString("id"));
            //可以通过修改密码重置时间，来注销特定Token的授权
            user.setLastPasswordResetDate(DateUtils.afterDays(-100, new Date()));
            user.setPassword(vo.getString("password").toLowerCase());
            return JwtUserFactory.create(user);
        } catch (Exception e) {
            throw new UsernameNotFoundException(String.format("getUserInfoByName Exception：%s.", e.getMessage()));
        }
    }

}
